package com.mine.frame.mylandemo.mvp.presenter

import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.blankj.utilcode.util.ToastUtils
import com.mine.frame.common.base.BasePresenter
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.entity.haobo.KeyNumberBean
import com.mine.frame.mylandemo.mvp.iview.IHaoBo
import kotlinx.android.synthetic.main.atv_haobo.*
import java.util.regex.Pattern

/**
 * @Date 2022/6/10
 * Description:
 */
class HaoBoPresenter(mIView: IHaoBo) : BasePresenter<IHaoBo>(mIView) {

    private var result = byteArrayOf()


    companion object {
        const val TAG = "红外解析:"
    }

    fun parseData(result: ByteArray) {
        when (mIView.getWhat()) {
            R.id.btnLearn -> {//学习指令
                parseLearn(result)
            }
            R.id.btnLearnLast -> {//最近学习过遥控器的序号

            }
            R.id.btnClearNumber -> {//清除所有按键数据
                parseClearKeyNumber(result)
            }
            R.id.btnBps -> {//修改波特率

            }
            R.id.btnSave -> {//备份红外数据

            }
            R.id.btnReset -> {//恢复出厂设置

            }

        }
    }

    /**
     * 解析：学习指令
     */
    private fun parseLearn(data: ByteArray) {
        if (isReceive(data)) {
            //指令结束
            Log.e(TAG, "指令结束")
            val str = String(result).replace("\r\n", "")
            if ("READING".equals(str, true)) {
                Log.e(TAG, "正在读取中")
                mIView.updateHint("请对准设备按遥控")
            } else if ("TIMEOUT".equals(str, true)) {
                Log.e(TAG, "超时")
                mIView.dismissLoading()
                ToastUtils.showShort("超时，请重试")
            } else if (isLearnResult(str)) {
                Log.e(TAG, "匹配到学习指令")
               onAddKeyNumber(str)
            } else {
                Log.e(TAG, "未匹配到学习指令")
                mIView.dismissLoading()
                ToastUtils.showShort("学习失败，请重试")
            }
            result = byteArrayOf()
        }
    }

    /**
     * 解析：清除所有按键数据
     */
    private fun parseClearKeyNumber(data: ByteArray){
        if (isReceive(data)) {
            val str = String(result).replace("\r\n", "")
            if ("EOK".equals(str ,true)){
                saveKeyNumberList(mutableListOf())
                mIView.onLearnSuccess(mutableListOf())
                ToastUtils.showShort("清除成功")
            }
        }
    }

    /**
     * 是否接收完数据
     */
    private fun isReceive(data: ByteArray): Boolean {
        result = result.plus(data)
        return if (result[result.size - 2] == 0x0D.toByte() && result[result.size - 1] == 0x0A.toByte()) {
            Log.e(TAG, "指令接收完成")
            true

        } else {
            Log.e(TAG, "指令未接收完")
            false
        }
    }

    /**
     * 是否匹配学习的结果
     */
    private fun isLearnResult(data: String): Boolean {
        val pattern = "(?<=RIR)\\d{3}"
        val matcher = Pattern.compile(pattern).toRegex()
        return matcher.containsMatchIn(data)
    }


    /**
     * 添加一个bean
     */
    private fun onAddKeyNumber(resultStr:String){
        val number = resultStr.substring(3)
        val bean = KeyNumberBean(number)
        bean.createResult = resultStr
        bean.name = mIView.getName()

        val list = getKeyNumberList()
        list.add(bean)
        saveKeyNumberList(list)
        mIView.onLearnSuccess(list)
    }


    /**
     * 获取已有的按键列表
     */
    fun getKeyNumberList():MutableList<KeyNumberBean>{
        val str = SPUtils.getInstance().getString("keyNumberList")
        return if (TextUtils.isEmpty(str)){
            mutableListOf()
        }else {
            GsonUtils.fromJson(str, GsonUtils.getListType(KeyNumberBean::class.java))
        }
    }

    /**
     * 保存列表数据
     */
    private fun saveKeyNumberList(list: MutableList<KeyNumberBean>){
        val str = GsonUtils.toJson(list)
        SPUtils.getInstance().put("keyNumberList" ,str)
    }

}